package jumpingnotes.util;

import java.awt.Rectangle;
import java.io.File;

import magick.ImageInfo;
import magick.MagickException;
import magick.MagickImage;
import java.util.UUID;

/**
*	1. Install ImageMagick: Run ImageMagick-6.4.2-7-Q16-windows-dll.exe.
*	2. copy jmagick.dll corresponding with the Q16 ImageMagick you installed to somewhere in your PATH.
**/

public class ImageHelper {

	public boolean zoom(String old_url, String new_url, double ratio)
	{
		//do some check
		if(ratio < 0)
			return false;
		try {
			File f = new File(old_url); 
			ImageInfo imgInfo = new ImageInfo( f.getAbsolutePath() );  
			MagickImage image = new MagickImage( imgInfo ); 
			double width = image.getDimension().getWidth(); 
			double height = image.getDimension().getHeight(); 
			MagickImage newImage = image.zoomImage((int)(width*ratio), (int)(height*ratio));
			newImage.setFileName(new_url); 
			newImage.writeImage(imgInfo);
		} catch (MagickException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} 

		return true;
	}
	
	public boolean crop(String old_url, String new_url,int x,int y, int width, int height)
	{
		//do some check
		if(x<0 || y<0 || width<0 || height<0)
			return false;
		try {
			File f = new File(old_url); 
			ImageInfo imgInfo = new ImageInfo( f.getAbsolutePath() );  
			MagickImage image = new MagickImage( imgInfo ); 
			int imageWidth = (int)image.getDimension().getWidth(); 
			int imageHeight = (int)image.getDimension().getHeight(); 
			if(x > imageWidth || y > imageHeight)
				return false;
			if(x+width > imageWidth) width = imageWidth-x;
			if(y+height > imageHeight) height = imageHeight-y;
			Rectangle r = new Rectangle(x,y,width,height);
			MagickImage newImage = image.cropImage(r);
			newImage.setFileName(new_url); 
			newImage.writeImage(imgInfo);
		} catch (MagickException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//System.out.println(System.getProperty("java.library.path"));
		ImageHelper ih = new ImageHelper();
		String file_path = "D:\\1447-WH~Old-World-Map-Posters.jpg";
		String new_url = "D:\\"+UUID.randomUUID().toString()+".jpg";
		//ih.zoom(file_path,new_url, 1.5);
		ih.crop(file_path, new_url, 0, 20, 300, 500);
	}

}
